﻿using AyuBookmark.Common.Models;
using AyuBookmark.WinForm.Commands;
using AyuBookmark.WinForm.Pipes;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AyuBookmark.WinForm.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private const string PipeName = "AyuBookmarkPipe";
        private readonly PipeClient _pipeClient;
        private Bookmark _selectedBookmark;
        private string _statusMessage;
        private bool _isConnected;
        private Category _selectedCategory;

        public event PropertyChangedEventHandler PropertyChanged;

        public MainViewModel()
        {
            _pipeClient = new PipeClient(PipeName);

            // 初始化命令
            RefreshCommand = new RelayCommand(async _ => await RefreshBookmarksAsync());
            AddBookmarkCommand = new RelayCommand(async _ => await AddBookmarkAsync());
            DeleteBookmarkCommand = new RelayCommand(async _ => await DeleteBookmarkAsync(),
                _ => SelectedBookmark != null);

            // 初始化集合
            Bookmarks = new ObservableCollection<Bookmark>();
            Categories = new ObservableCollection<Category>
            {
                new Category { Name = "全部", Id = -1 }, // 虚拟分类
                new Category { Name = "工作", Id = 1, Color = "#4285F4" },
                new Category { Name = "学习", Id = 2, Color = "#34A853" },
                new Category { Name = "娱乐", Id = 3, Color = "#EA4335" }
            };

            SelectedCategory = Categories.First();
            _ = RefreshBookmarksAsync();
        }

        #region 数据绑定属性
        public ObservableCollection<Bookmark> Bookmarks { get; }
        public ObservableCollection<Category> Categories { get; }

        public Bookmark SelectedBookmark
        {
            get => _selectedBookmark;
            set
            {
                _selectedBookmark = value;
                OnPropertyChanged(nameof(SelectedBookmark));
                ((RelayCommand)DeleteBookmarkCommand).RaiseCanExecuteChanged();
            }
        }

        public Category SelectedCategory
        {
            get => _selectedCategory;
            set
            {
                _selectedCategory = value;
                OnPropertyChanged(nameof(SelectedCategory));
                _ = RefreshBookmarksAsync();
            }
        }

        public string StatusMessage
        {
            get => _statusMessage;
            set
            {
                _statusMessage = value;
                OnPropertyChanged(nameof(StatusMessage));
            }
        }

        public bool IsConnected
        {
            get => _isConnected;
            set
            {
                _isConnected = value;
                OnPropertyChanged(nameof(IsConnected));
            }
        }

        public string NewBookmarkUrl { get; set; }
        public string NewBookmarkTitle { get; set; }
        #endregion

        #region 命令
        public IRelayCommand RefreshCommand { get; }
        public IRelayCommand AddBookmarkCommand { get; }
        public IRelayCommand DeleteBookmarkCommand { get; }
        #endregion

        #region 核心方法
        public async Task RefreshBookmarksAsync()
        {
            try
            {
                StatusMessage = "正在加载书签...";
                var response = await _pipeClient.SendMessageAsync(
                    JsonSerializer.Serialize(new { Command = "GetAllBookmarks" }));

                if (!string.IsNullOrEmpty(response))
                {
                    var bookmarks = JsonSerializer.Deserialize<Bookmark[]>(response);
                    Bookmarks.Clear();
                    foreach (var item in bookmarks.Where(FilterByCategory))
                    {
                        // 确保分类对象引用一致
                        item.Category = Categories.FirstOrDefault(c => c.Id == item.Category?.Id) ?? item.Category;
                        Bookmarks.Add(item);
                    }

                    StatusMessage = $"加载完成，共 {Bookmarks.Count} 条书签";
                    IsConnected = true;
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载失败: {ex.Message}";
                IsConnected = false;
            }
        }

        public async Task AddBookmarkAsync()
        {
            if (string.IsNullOrWhiteSpace(NewBookmarkUrl))
            {
                StatusMessage = "URL不能为空";
                return;
            }

            try
            {
                var bookmark = new Bookmark
                {
                    Url = NewBookmarkUrl,
                    Title = string.IsNullOrWhiteSpace(NewBookmarkTitle)
                        ? GetDefaultTitle(NewBookmarkUrl)
                        : NewBookmarkTitle,
                    Category = SelectedCategory.Id == -1 ? null : SelectedCategory, // 处理"全部"分类
                    CreatedTime = DateTime.Now
                };

                var response = await _pipeClient.SendMessageAsync(
                    JsonSerializer.Serialize(new
                    {
                        Command = "AddBookmark",
                        Data = bookmark
                    }));

                if (response?.Contains("success", StringComparison.OrdinalIgnoreCase) == true)
                {
                    Bookmarks.Add(bookmark);
                    NewBookmarkUrl = NewBookmarkTitle = string.Empty;
                    OnPropertyChanged(nameof(NewBookmarkUrl));
                    OnPropertyChanged(nameof(NewBookmarkTitle));

                    StatusMessage = "书签添加成功";
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"添加失败: {ex.Message}";
            }
        }

        public async Task DeleteBookmarkAsync()
        {
            if (SelectedBookmark == null) return;

            if (MessageBox.Show($"确定删除 '{SelectedBookmark.Title}'?",
                "确认", MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            try
            {
                var response = await _pipeClient.SendMessageAsync(
                    JsonSerializer.Serialize(new
                    {
                        Command = "DeleteBookmark",
                        Data = new { Id = SelectedBookmark.Id }
                    }));

                if (response?.Contains("success", StringComparison.OrdinalIgnoreCase) == true)
                {
                    Bookmarks.Remove(SelectedBookmark);
                    StatusMessage = "书签已删除";
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"删除失败: {ex.Message}";
            }
        }
        #endregion

        #region 辅助方法
        private bool FilterByCategory(Bookmark bookmark)
        {
            return SelectedCategory.Id == -1 || // "全部"分类
                   (bookmark.Category != null && bookmark.Category.Id == SelectedCategory.Id);
        }

        private string GetDefaultTitle(string url)
        {
            try
            {
                var uri = new Uri(url);
                return uri.Host.Replace("www.", "").Replace(".com", "");
            }
            catch
            {
                return "未命名书签";
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
}